import { editCategory } from '@/services/ant-design-pro/api';
import {
  ProFormDigit,
  ProFormText,
  ProForm,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { message, Modal } from 'antd';
import React, { cloneElement, useCallback, useState } from 'react';

// export type FormValueType = {
//   target?: string;
//   template?: string;
//   type?: string;
//   time?: string;
//   frequency?: string;
// } & Partial<API.AssetsListItem>;

export type UpdateFormProps = {
  trigger?: JSX.Element;
  onOk?: () => void;
  values: API.CategoryListItem | undefined;
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  //这里的values有key
  const { onOk, values: selectedrow, trigger } = props;

  const intl = useIntl();

  const [open, setOpen] = useState(false);

  const [messageApi, contextHolder] = message.useMessage();

  const { run } = useRequest(editCategory, {
    manual: true,
    onSuccess: () => {
      messageApi.success('修改成功');
      onOk?.();
    },
    onError: () => {
      messageApi.error('修改失败!');
    },
  });

  const onCancel = useCallback(() => {
    setOpen(false);
  }, []);

  const onOpen = useCallback(() => {
    setOpen(true);
  }, []);

  const onFinish = useCallback(
    async (values?: API.CategoryListItem | undefined) => {

      if (values && selectedrow) {
        //这里的values没有key，所以需要加上，后端需要key才能update
        values.key = selectedrow.key;
        await run(values);
        onCancel();
      }
    },
    [onCancel, run],
  );

  //请求后端类别数据
  // const fetchData = async (categoryClass: number) => {
  //   const response = await assetsCategory({ categoryclass: categoryClass });
  //   return response.map((item: any) => ({
  //     label: item.description, // 显示的文本  
  //     value: item.type,       // 实际的值  
  //   }));
  // };
  // // ProFormSelect 的 request 辅助函数  
  // const fetchvaluelable = async (categoryClass: number) => {
  //   return await fetchData(categoryClass);
  // };

  return (
    <>
      {contextHolder}
      {trigger
        ? cloneElement(trigger, {
          onClick: onOpen,
        })
        : null}
      <Modal
        width={640}
        // bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title={intl.formatMessage({
          id: 'pages.category.editForm.title',
          defaultMessage: '修改类别信息',
        })}
        open={open}
        footer={null} // Assuming you want to handle submission differently  
        onCancel={onCancel}
      >
        <ProForm
          // 
          initialValues={{
            ...selectedrow,
            // assetsclass: String(selectedrow?.assetsclass), // 将 assetsclass 转换为字符串  valueEnum是字符串形式 但如果是动态获取则已经更改为字符串了
            // assetsname: String(selectedrow?.assetsname) // 将 assetsname 转换为字符串  
          }}
          onFinish={onFinish} // Handle form submission here  
        >
          <ProFormDigit
            name="category"
            disabled={true}
            label={intl.formatMessage({
              id: 'pages.category.Form.category',
              defaultMessage: '类别号',
            })}
            width="md"
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.category.Form.ruleName.category"
                    defaultMessage="请输入类别号！"
                  />
                ),
              },
              //确保输入为整数
              {
                validator: (_, value) => {
                  if (value !== undefined && !Number.isInteger(value)) {
                    return Promise.reject(
                      <FormattedMessage
                        id="pages.Form.ruleName.Integer"
                        defaultMessage="请输入整数！"
                      />
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
          />
          <ProFormDigit
            name="type"
            disabled={true}
            label={intl.formatMessage({
              id: 'pages.category.Form.type',
              defaultMessage: '类型号',
            })}
            width="md"
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.category.Form.ruleName.type"
                    defaultMessage="请输入类型号！"
                  />
                ),
              },
                //确保输入为整数
                {
                  validator: (_, value) => {
                    if (value !== undefined && !Number.isInteger(value)) {
                      return Promise.reject(
                        <FormattedMessage
                          id="pages.Form.ruleName.Integer"
                          defaultMessage="请输入整数！"
                        />
                      );
                    }
                    return Promise.resolve();
                  },
                },
         
            ]}
          />
         
          <ProFormText
            name="description"
            label={intl.formatMessage({
              id: 'pages.category.Form.description',
              defaultMessage: '描述',
            })}
            width="md"
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.category.Form.ruleName.description"
                    defaultMessage="请输入描述！"
                  />
                ),
              },
            ]}
          />
        </ProForm>
      </Modal>
    </>
  );
};

export default UpdateForm;
